<?php
namespace app\controller;

use app\BaseController;
use app\controller\v1\System;
use think\App;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

class Purchase extends BaseController
{
    /**
     * 获取采购订单列表
     */
    public function getPurchaseOrderList()
    {
        // 获取参数
        $page = (int)Request::param('page', 1);
        $limit = (int)Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $start_date = Request::param('start_date', '');
        $end_date = Request::param('end_date', '');
        
        // 记录请求参数
        file_put_contents(__DIR__ . '/log250825/purchase_order_list.log', date('Y-m-d H:i:s') . ' - 请求参数: ' . json_encode([
            'page' => $page,
            'limit' => $limit,
            'search' => $search,
            'status' => $status,
            'start_date' => $start_date,
            'end_date' => $end_date
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 构建查询条件
        $where = [];
        
        if (!empty($search)) {
            $where[] = ['po.order_no|po.remark', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['po.status', '=', $status];
        }
        
        if (!empty($start_date) && !empty($end_date)) {
            $where[] = ['po.order_date', 'between', [$start_date, $end_date]];
        } else if (!empty($start_date)) {
            $where[] = ['po.order_date', '>=', $start_date];
        } else if (!empty($end_date)) {
            $where[] = ['po.order_date', '<=', $end_date];
        }
        
        // 查询总数
        $count = Db::name('purchase_order')
            ->alias('po')
            ->where($where)
            ->count();
        
        // 查询数据
        $list = Db::name('purchase_order')
            ->alias('po')
            ->field('po.*, s.supplier_name, u.realname as operator_name')
            ->leftJoin('supplier s', 'po.supplier_id = s.id')
            ->leftJoin('user u', 'po.operator_id = u.id')
            ->where($where)
            ->order('po.id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        
        // 记录响应数据
        file_put_contents(__DIR__ . '/log250825/purchase_order_list.log', date('Y-m-d H:i:s') . ' - 响应数据: 总数=' . $count . ', 列表数=' . count($list) . PHP_EOL, FILE_APPEND);
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $count
            ]
        ]);
    }
    
    /**
     * 添加采购订单
     */
    public function addPurchaseOrder()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 检查数据类型
        if (isset($data['details'])) {
            if (!is_array($data['details'])) {
                file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - details不是数组: ' . gettype($data['details']) . PHP_EOL, FILE_APPEND);
                // 尝试解码JSON字符串
                if (is_string($data['details'])) {
                    $data['details'] = json_decode($data['details'], true);
                    file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 解码后的details: ' . json_encode($data['details'], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
            }
        }
        
        // 验证主表数据
        $validate = Validate::rule([
            'supplier_id' => 'require|number',
            'order_date' => 'require|date',
            'delivery_date' => 'require|date',
            'payment_method' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }

        $user= $this->getUserInfo();

        // 开启事务
        Db::startTrans();
        try {
            // 生成订单号
            $data['order_no'] = 'PO' . date('YmdHis') . rand(100, 999);

            // 处理主表数据
            $mainData = [
                'order_no' => $data['order_no'],
                'supplier_id' => $data['supplier_id'],
                'order_date' => $data['order_date'],
                'delivery_date' => $data['delivery_date'],
                'payment_method' => $data['payment_method'],
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'operator_id' => $user['id'] ?? 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录主表数据
            file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 主表数据: ' . json_encode($mainData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 插入主表数据
            $orderId = Db::name('purchase_order')->insertGetId($mainData);
            
            // 处理明细表数据
            if (!empty($data['details']) && is_array($data['details'])) {
                $totalAmount = 0;
                $detailsData = [];
                
                // 查询表结构
                $tableInfo = Db::query("SHOW COLUMNS FROM fy_purchase_order_detail");
                $fields = array_column($tableInfo, 'Field');
                file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 表字段: ' . json_encode($fields, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                
                foreach ($data['details'] as $detail) {
                    // 记录每条明细数据
                    file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 处理明细: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                    
                    // 验证明细数据
                    if (empty($detail['material_id']) || !isset($detail['quantity']) || !isset($detail['unit_price'])) {
                        file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 明细数据验证失败: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                        throw new \Exception('物料ID、数量和单价不能为空');
                    }
                    
                    // 确保数值类型正确
                    $material_id = intval($detail['material_id']);
                    $quantity = floatval($detail['quantity']);
                    $unit_price = floatval($detail['unit_price']);
                    $amount = $unit_price * $quantity;
                    $totalAmount += $amount;
                    
                    // 准备明细数据
                    $detailData = [
                        'order_id' => $orderId,
                        'material_id' => $material_id,
                        'quantity' => $quantity,
                        'unit_price' => $unit_price,
                        'amount' => $amount,
                        'delivery_date' => $detail['delivery_date'] ?? $data['delivery_date'],
                        'remark' => $detail['remark'] ?? '',
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $detailsData[] = $detailData;
                }
                
                // 记录明细数据
                file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 明细数据: ' . json_encode($detailsData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                
                // 批量插入明细数据
                if (!empty($detailsData)) {
                    Db::name('purchase_order_detail')->insertAll($detailsData);
                }
                
                // 更新主表总金额
                Db::name('purchase_order')->where('id', $orderId)->update([
                    'total_amount' => $totalAmount,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            } else {
                file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 没有明细数据或格式不正确: ' . json_encode($data['details'] ?? null, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $orderId]]);
        } catch (\Exception $e) {
            Db::rollback();
            file_put_contents(__DIR__ . '/log250825/purchase_order_add.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新采购订单
     */
    public function updatePurchaseOrder()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 检查数据类型
        if (isset($data['details'])) {
            if (!is_array($data['details'])) {
                file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - details不是数组: ' . gettype($data['details']) . PHP_EOL, FILE_APPEND);
                // 尝试解码JSON字符串
                if (is_string($data['details'])) {
                    $data['details'] = json_decode($data['details'], true);
                    file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 解码后的details: ' . json_encode($data['details'], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
            }
        }
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_id' => 'require|number',
            'order_date' => 'require|date',
            'delivery_date' => 'require|date',
            'payment_method' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }
        
        // 检查订单是否存在
        $order = Db::name('purchase_order')->where('id', $data['id'])->find();
        if (!$order) {
            return json(['code' => 404, 'msg' => '订单不存在']);
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 处理主表数据
            $mainData = [
                'supplier_id' => $data['supplier_id'],
                'order_date' => $data['order_date'],
                'delivery_date' => $data['delivery_date'],
                'payment_method' => $data['payment_method'],
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录主表数据
            file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 主表数据: ' . json_encode($mainData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 更新主表数据
            Db::name('purchase_order')->where('id', $data['id'])->update($mainData);
            
            // 处理明细表数据
            if (!empty($data['details']) && is_array($data['details'])) {
                // 删除原有明细
                Db::name('purchase_order_detail')->where('order_id', $data['id'])->delete();
                
                $totalAmount = 0;
                $detailsData = [];
                
                foreach ($data['details'] as $detail) {
                    // 验证明细数据
                    if (empty($detail['material_id']) || !isset($detail['quantity']) || !isset($detail['unit_price'])) {
                        file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 明细数据验证失败: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                        throw new \Exception('物料ID、数量和单价不能为空');
                    }
                    
                    $amount = ($detail['unit_price'] ?? 0) * ($detail['quantity'] ?? 0);
                    $totalAmount += $amount;
                    
                    // 准备明细数据
                    $detailData = [
                        'order_id' => $data['id'],
                        'material_id' => $detail['material_id'],
                        'quantity' => $detail['quantity'],
                        'unit_price' => $detail['unit_price'],
                        'amount' => $amount,
                        'delivery_date' => $detail['delivery_date'] ?? $data['delivery_date'],
                        'remark' => $detail['remark'] ?? '',
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $detailsData[] = $detailData;
                }
                
                // 批量插入明细数据
                if (!empty($detailsData)) {
                    Db::name('purchase_order_detail')->insertAll($detailsData);
                }
                
                // 更新主表总金额
                Db::name('purchase_order')->where('id', $data['id'])->update([
                    'total_amount' => $totalAmount,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            file_put_contents(__DIR__ . '/log250825/purchase_order_update.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除采购订单
     */
    public function deletePurchaseOrder()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        Db::startTrans();
        try {
            if (!empty($ids)) {
                // 批量删除
                $idArray = explode(',', $ids);
                foreach ($idArray as $orderId) {
                    // 删除订单明细
                    Db::name('purchase_order_detail')->where('order_id', $orderId)->delete();
                    // 删除订单
                    Db::name('purchase_order')->delete($orderId);
                }
            } else {
                // 单个删除
                // 删除订单明细
                Db::name('purchase_order_detail')->where('order_id', $id)->delete();
                // 删除订单
                Db::name('purchase_order')->delete($id);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取采购订单详情
     */
    public function getPurchaseOrderDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 获取订单主表数据
        $order = Db::name('purchase_order')
            ->alias('po')
            ->field('po.*, s.supplier_name, u.realname as operator_name')
            ->leftJoin('supplier s', 'po.supplier_id = s.id')
            ->leftJoin('user u', 'po.operator_id = u.id')
            ->where('po.id', $id)
            ->find();
        
        if (!$order) {
            return json(['code' => 404, 'msg' => '订单不存在']);
        }
        
        // 获取订单明细数据
        $details = Db::name('purchase_order_detail')
            ->alias('pod')
            ->field('pod.*, mc.material_name')
            ->leftJoin('material_category mc', 'pod.material_id = mc.id')
            ->where('pod.order_id', $id)
            ->select()
            ->toArray();
        
        $order['details'] = $details;
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $order]);
    }
    
    /**
     * 获取采购订单列表（简化版，用于下拉选择）
     */
    public function getPurchaseOrderSelectList()
    {
        $list = Db::name('purchase_order')
            ->field('id, order_no, supplier_id, total_amount')
            ->where('status', '<>', 0) // 排除已删除的订单
            ->order('id', 'desc')
            ->select()
            ->toArray();
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取采购发票列表
     */
    public function getPurchaseInvoiceList()
    {
        // 获取参数
        $page = (int)Request::param('page', 1);
        $limit = (int)Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $start_date = Request::param('start_date', '');
        $end_date = Request::param('end_date', '');
        
        // 记录请求参数
        file_put_contents(__DIR__ . '/log250825/purchase_invoice_list.log', date('Y-m-d H:i:s') . ' - 请求参数: ' . json_encode([
            'page' => $page,
            'limit' => $limit,
            'search' => $search,
            'status' => $status,
            'start_date' => $start_date,
            'end_date' => $end_date
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 构建查询条件
        $where = [];
        
        if (!empty($search)) {
            $where[] = ['pi.invoice_no|po.order_no', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['pi.status', '=', $status];
        }
        
        if (!empty($start_date) && !empty($end_date)) {
            $where[] = ['pi.invoice_date', 'between', [$start_date, $end_date]];
        } else if (!empty($start_date)) {
            $where[] = ['pi.invoice_date', '>=', $start_date];
        } else if (!empty($end_date)) {
            $where[] = ['pi.invoice_date', '<=', $end_date];
        }
        
        // 查询总数
        $count = Db::name('purchase_invoice')
            ->alias('pi')
            ->leftJoin('purchase_order po', 'pi.order_id = po.id')
            ->where($where)
            ->count();
        
        // 查询数据
        $list = Db::name('purchase_invoice')
            ->alias('pi')
            ->field('pi.*, po.order_no, s.supplier_name, u.realname as operator_name')
            ->leftJoin('purchase_order po', 'pi.order_id = po.id')
            ->leftJoin('supplier s', 'pi.supplier_id = s.id')
            ->leftJoin('user u', 'pi.operator_id = u.id')
            ->where($where)
            ->order('pi.id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        
        // 记录响应数据
        file_put_contents(__DIR__ . '/log250825/purchase_invoice_list.log', date('Y-m-d H:i:s') . ' - 响应数据: 总数=' . $count . ', 列表数=' . count($list) . PHP_EOL, FILE_APPEND);
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $count
            ]
        ]);
    }
    
    /**
     * 添加采购发票
     */
    public function addPurchaseInvoice()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_invoice_add.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 验证数据
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'supplier_id' => 'require|number',
            'invoice_date' => 'require|date',
            'amount' => 'require|float',
            'invoice_title' => 'require',
            'tax_no' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_add.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }
        
        try {
            // 生成发票号
            $data['invoice_no'] = 'INV' . date('YmdHis') . rand(100, 999);
            
            // 准备数据
            $insertData = [
                'invoice_no' => $data['invoice_no'],
                'order_id' => $data['order_id'],
                'supplier_id' => $data['supplier_id'],
                'invoice_date' => $data['invoice_date'],
                'amount' => $data['amount'],
                'invoice_title' => $data['invoice_title'],
                'tax_no' => $data['tax_no'],
                'bank_account' => $data['bank_account'] ?? '',
                'contact_person' => $data['contact_person'] ?? '',
                'contact_phone' => $data['contact_phone'] ?? '',
                'contact_email' => $data['contact_email'] ?? '',
                'mailing_address' => $data['mailing_address'] ?? '',
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'operator_id' => $data['operator_id'] ?? 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录插入数据
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_add.log', date('Y-m-d H:i:s') . ' - 插入数据: ' . json_encode($insertData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 插入数据
            $invoiceId = Db::name('purchase_invoice')->insertGetId($insertData);
            
            return json(['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $invoiceId]]);
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_add.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新采购发票
     */
    public function updatePurchaseInvoice()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_invoice_update.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 验证数据
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'supplier_id' => 'require|number',
            'invoice_date' => 'require|date',
            'amount' => 'require|float',
            'invoice_title' => 'require',
            'tax_no' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_update.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }
        
        // 检查发票是否存在
        $invoice = Db::name('purchase_invoice')->where('id', $data['id'])->find();
        if (!$invoice) {
            return json(['code' => 404, 'msg' => '发票不存在']);
        }
        
        try {
            // 准备更新数据
            $updateData = [
                'order_id' => $data['order_id'],
                'supplier_id' => $data['supplier_id'],
                'invoice_date' => $data['invoice_date'],
                'amount' => $data['amount'],
                'invoice_title' => $data['invoice_title'],
                'tax_no' => $data['tax_no'],
                'bank_account' => $data['bank_account'] ?? '',
                'contact_person' => $data['contact_person'] ?? '',
                'contact_phone' => $data['contact_phone'] ?? '',
                'contact_email' => $data['contact_email'] ?? '',
                'mailing_address' => $data['mailing_address'] ?? '',
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录更新数据
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_update.log', date('Y-m-d H:i:s') . ' - 更新数据: ' . json_encode($updateData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 更新数据
            Db::name('purchase_invoice')->where('id', $data['id'])->update($updateData);
            
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/purchase_invoice_update.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除采购发票
     */
    public function deletePurchaseInvoice()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            if (!empty($ids)) {
                // 批量删除
                $idArray = explode(',', $ids);
                Db::name('purchase_invoice')->whereIn('id', $idArray)->delete();
            } else {
                // 单个删除
                Db::name('purchase_invoice')->delete($id);
            }
            
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 400, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取采购发票详情
     */
    public function getPurchaseInvoiceDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 获取发票数据
        $invoice = Db::name('purchase_invoice')
            ->alias('pi')
            ->field('pi.*, po.order_no, s.supplier_name, u.realname as operator_name')
            ->leftJoin('purchase_order po', 'pi.order_id = po.id')
            ->leftJoin('supplier s', 'pi.supplier_id = s.id')
            ->leftJoin('user u', 'pi.operator_id = u.id')
            ->where('pi.id', $id)
            ->find();
        
        if (!$invoice) {
            return json(['code' => 404, 'msg' => '发票不存在']);
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $invoice]);
    }

    /**
     * 获取采购退货列表
     */
    public function getPurchaseReturnList()
    {
        // 获取参数
        $page = (int)Request::param('page', 1);
        $limit = (int)Request::param('limit', 10);
        $search = Request::param('search', '');
        $status = Request::param('status', '');
        $start_date = Request::param('start_date', '');
        $end_date = Request::param('end_date', '');
        
        // 记录请求参数
        file_put_contents(__DIR__ . '/log250825/purchase_return_list.log', date('Y-m-d H:i:s') . ' - 请求参数: ' . json_encode([
            'page' => $page,
            'limit' => $limit,
            'search' => $search,
            'status' => $status,
            'start_date' => $start_date,
            'end_date' => $end_date
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 构建查询条件
        $where = [];
        
        if (!empty($search)) {
            $where[] = ['pr.return_no|po.order_no', 'like', "%{$search}%"];
        }
        
        if ($status !== '') {
            $where[] = ['pr.status', '=', $status];
        }
        
        if (!empty($start_date) && !empty($end_date)) {
            $where[] = ['pr.return_date', 'between', [$start_date, $end_date]];
        } else if (!empty($start_date)) {
            $where[] = ['pr.return_date', '>=', $start_date];
        } else if (!empty($end_date)) {
            $where[] = ['pr.return_date', '<=', $end_date];
        }
        
        // 查询总数
        $count = Db::name('purchase_return')
            ->alias('pr')
            ->leftJoin('purchase_order po', 'pr.order_id = po.id')
            ->where($where)
            ->count();
        
        // 查询数据
        $list = Db::name('purchase_return')
            ->alias('pr')
            ->field('pr.*, po.order_no, s.supplier_name, u.realname as operator_name')
            ->leftJoin('purchase_order po', 'pr.order_id = po.id')
            ->leftJoin('supplier s', 'pr.supplier_id = s.id')
            ->leftJoin('user u', 'pr.operator_id = u.id')
            ->where($where)
            ->order('pr.id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
        
        // 记录响应数据
        file_put_contents(__DIR__ . '/log250825/purchase_return_list.log', date('Y-m-d H:i:s') . ' - 响应数据: 总数=' . $count . ', 列表数=' . count($list) . PHP_EOL, FILE_APPEND);
        
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $count
            ]
        ]);
    }
    
    /**
     * 添加采购退货
     */
    public function addPurchaseReturn()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 检查数据类型
        if (isset($data['details'])) {
            if (!is_array($data['details'])) {
                file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - details不是数组: ' . gettype($data['details']) . PHP_EOL, FILE_APPEND);
                // 尝试解码JSON字符串
                if (is_string($data['details'])) {
                    $data['details'] = json_decode($data['details'], true);
                    file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 解码后的details: ' . json_encode($data['details'], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
            }
        }
        
        // 验证主表数据
        $validate = Validate::rule([
            'order_id' => 'require|number',
            'supplier_id' => 'require|number',
            'return_date' => 'require|date',
            'reason' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 生成退货单号
            $data['return_no'] = 'PR' . date('YmdHis') . rand(100, 999);
            
            // 处理主表数据
            $mainData = [
                'return_no' => $data['return_no'],
                'order_id' => $data['order_id'],
                'supplier_id' => $data['supplier_id'],
                'return_date' => $data['return_date'],
                'reason' => $data['reason'],
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'operator_id' => $data['operator_id'] ?? 0,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录主表数据
            file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 主表数据: ' . json_encode($mainData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 插入主表数据
            $returnId = Db::name('purchase_return')->insertGetId($mainData);
            
            // 处理明细表数据
            if (!empty($data['details']) && is_array($data['details'])) {
                $totalAmount = 0;
                $detailsData = [];
                
                // 查询表结构
                $tableInfo = Db::query("SHOW COLUMNS FROM fy_purchase_return_detail");
                $fields = array_column($tableInfo, 'Field');
                file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 表字段: ' . json_encode($fields, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                
                foreach ($data['details'] as $detail) {
                    // 记录每条明细数据
                    file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 处理明细: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                    
                    // 验证明细数据
                    if (empty($detail['material_id']) || !isset($detail['quantity']) || !isset($detail['unit_price'])) {
                        file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 明细数据验证失败: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                        throw new \Exception('物料ID、数量和单价不能为空');
                    }
                    
                    // 确保数值类型正确
                    $material_id = intval($detail['material_id']);
                    $quantity = floatval($detail['quantity']);
                    $unit_price = floatval($detail['unit_price']);
                    $amount = $unit_price * $quantity;
                    $totalAmount += $amount;
                    
                    // 准备明细数据
                    $detailData = [
                        'return_id' => $returnId,
                        'material_id' => $material_id,
                        'quantity' => $quantity,
                        'unit_price' => $unit_price,
                        'amount' => $amount,
                        'remark' => $detail['remark'] ?? '',
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $detailsData[] = $detailData;
                }
                
                // 记录明细数据
                file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 明细数据: ' . json_encode($detailsData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                
                // 批量插入明细数据
                if (!empty($detailsData)) {
                    Db::name('purchase_return_detail')->insertAll($detailsData);
                }
                
                // 更新主表总金额
                Db::name('purchase_return')->where('id', $returnId)->update([
                    'total_amount' => $totalAmount,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            } else {
                file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 没有明细数据或格式不正确: ' . json_encode($data['details'] ?? null, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '添加成功', 'data' => ['id' => $returnId]]);
        } catch (\Exception $e) {
            Db::rollback();
            file_put_contents(__DIR__ . '/log250825/purchase_return_add.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新采购退货
     */
    public function updatePurchaseReturn()
    {
        $data = Request::post();
        
        // 记录接收到的数据
        file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 接收到的数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        // 检查数据类型
        if (isset($data['details'])) {
            if (!is_array($data['details'])) {
                file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - details不是数组: ' . gettype($data['details']) . PHP_EOL, FILE_APPEND);
                // 尝试解码JSON字符串
                if (is_string($data['details'])) {
                    $data['details'] = json_decode($data['details'], true);
                    file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 解码后的details: ' . json_encode($data['details'], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                }
            }
        }
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'order_id' => 'require|number',
            'supplier_id' => 'require|number',
            'return_date' => 'require|date',
            'reason' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            $errorMsg = $validate->getError();
            file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $errorMsg . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $errorMsg]);
        }
        
        // 检查退货单是否存在
        $returnOrder = Db::name('purchase_return')->where('id', $data['id'])->find();
        if (!$returnOrder) {
            return json(['code' => 404, 'msg' => '退货单不存在']);
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 处理主表数据
            $mainData = [
                'order_id' => $data['order_id'],
                'supplier_id' => $data['supplier_id'],
                'return_date' => $data['return_date'],
                'reason' => $data['reason'],
                'status' => $data['status'],
                'remark' => $data['remark'] ?? '',
                'update_time' => date('Y-m-d H:i:s')
            ];
            
            // 记录主表数据
            file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 主表数据: ' . json_encode($mainData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            // 更新主表数据
            Db::name('purchase_return')->where('id', $data['id'])->update($mainData);
            
            // 处理明细表数据
            if (!empty($data['details']) && is_array($data['details'])) {
                // 删除原有明细
                Db::name('purchase_return_detail')->where('return_id', $data['id'])->delete();
                
                $totalAmount = 0;
                $detailsData = [];
                
                foreach ($data['details'] as $detail) {
                    // 验证明细数据
                    if (empty($detail['material_id']) || !isset($detail['quantity']) || !isset($detail['unit_price'])) {
                        file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 明细数据验证失败: ' . json_encode($detail, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                        throw new \Exception('物料ID、数量和单价不能为空');
                    }
                    
                    $amount = ($detail['unit_price'] ?? 0) * ($detail['quantity'] ?? 0);
                    $totalAmount += $amount;
                    
                    // 准备明细数据
                    $detailData = [
                        'return_id' => $data['id'],
                        'material_id' => $detail['material_id'],
                        'quantity' => $detail['quantity'],
                        'unit_price' => $detail['unit_price'],
                        'amount' => $amount,
                        'remark' => $detail['remark'] ?? '',
                        'create_time' => date('Y-m-d H:i:s'),
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    
                    $detailsData[] = $detailData;
                }
                
                // 批量插入明细数据
                if (!empty($detailsData)) {
                    Db::name('purchase_return_detail')->insertAll($detailsData);
                }
                
                // 更新主表总金额
                Db::name('purchase_return')->where('id', $data['id'])->update([
                    'total_amount' => $totalAmount,
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Db::rollback();
            file_put_contents(__DIR__ . '/log250825/purchase_return_update.log', date('Y-m-d H:i:s') . ' - 异常: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除采购退货
     */
    public function deletePurchaseReturn()
    {
        $id = Request::param('id');
        $ids = Request::param('ids');
        
        if (empty($id) && empty($ids)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        Db::startTrans();
        try {
            if (!empty($ids)) {
                // 批量删除
                $idArray = explode(',', $ids);
                foreach ($idArray as $returnId) {
                    // 删除退货单明细
                    Db::name('purchase_return_detail')->where('return_id', $returnId)->delete();
                    // 删除退货单
                    Db::name('purchase_return')->delete($returnId);
                }
            } else {
                // 单个删除
                // 删除退货单明细
                Db::name('purchase_return_detail')->where('return_id', $id)->delete();
                // 删除退货单
                Db::name('purchase_return')->delete($id);
            }
            
            Db::commit();
            return json(['code' => 200, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 400, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取采购退货详情
     */
    public function getPurchaseReturnDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 获取退货单主表数据
        $returnOrder = Db::name('purchase_return')
            ->alias('pr')
            ->field('pr.*, po.order_no, s.supplier_name, u.realname as operator_name')
            ->leftJoin('purchase_order po', 'pr.order_id = po.id')
            ->leftJoin('supplier s', 'pr.supplier_id = s.id')
            ->leftJoin('user u', 'pr.operator_id = u.id')
            ->where('pr.id', $id)
            ->find();
        
        if (!$returnOrder) {
            return json(['code' => 404, 'msg' => '退货单不存在']);
        }
        
        // 获取退货单明细数据
        $details = Db::name('purchase_return_detail')
            ->alias('prd')
            ->field('prd.*, mc.material_name')
            ->leftJoin('material_category mc', 'prd.material_id = mc.id')
            ->where('prd.return_id', $id)
            ->select()
            ->toArray();
        
        $returnOrder['details'] = $details;
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $returnOrder]);
    }
} 